package com.zx._02_thread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * 计算1+2+3.....+100
 *
 * @author zhangxue
 */
public class CountTask extends RecursiveTask<Integer> {

    private static final long serialVersionUID = -3170783753270625094L;

    /**
     * 阈值
     */
    private static final int THRESHOLD = 10;

    private int start;//第一个计算的数字

    private int end;//最后一个计算的数字

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 生成一个计算任务
        CountTask countTask = new CountTask(1, 100);
        // 提交一个任务
        Future<Integer> submit = forkJoinPool.submit(countTask);

        try {
            System.out.println(submit.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Integer compute() {
        int sum = 0;

        //如果任务足够小就开始计算
        boolean canCompute = (end - start) <= THRESHOLD;

        if (canCompute) {
            // int a = 1 / 0;
            System.out.println("开始计算：" + start + ", " + end);
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {//任务大的话，就继续分割任务,这里因为将任务分为2个
            int middle = (start + end) / 2;
            CountTask leftTask = new CountTask(start, middle);
            CountTask rightTask = new CountTask(middle + 1, end);
            //执行任务
            leftTask.fork();
            rightTask.fork();

            //获得子任务的结果
            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();

            sum = leftResult + rightResult;

        }

        return sum;
    }


}
